﻿using System.Collections.Generic;
using System.Diagnostics;

namespace Framework.Diagnostics
{
    /// <summary>
    /// 用于做性能计数器监控性能指标
    /// </summary>
    public class PerfCounterRepositoryBase
    {
        // The Performance Counter Mapping
        //      Key : Performance Counter Alias
        //      Value : Performance Counter Object
        protected SortedDictionary<string, PerformanceCounter> CounterMap =
            new SortedDictionary<string, PerformanceCounter>();

        /// <summary>
        /// Add Performance Counter into Mapping
        /// 
        /// The Alias is same as counterName
        /// </summary>
        /// <param name="categoryName">Performance Counter Catagory</param>
        /// <param name="counterName">Performance Counter Name</param>
        public void AddPerfCounter(string categoryName, string counterName)
        {
            var counter = new PerformanceCounter(categoryName, counterName) {ReadOnly = false};
            CounterMap.Add(counterName, counter);
        }

        /// <summary>
        /// Add Performance Counter into Mapping using Specified Alias
        /// </summary>
        /// <param name="alias"></param>
        /// <param name="categoryName">Performance Counter Catagory</param>
        /// <param name="counterName">Performance Counter Name</param>
        public void AddPerfCounter(string alias, string categoryName, string counterName)
        {
            var counter = new PerformanceCounter(categoryName, counterName) {ReadOnly = false};
            CounterMap.Add(alias, counter);
        }

        /// <summary>
        /// Increase Performance Counter Value by 1
        /// </summary>
        /// <param name="alias">Performance Counter Alias</param>
        public void IncreaseCounter(string alias)
        {
            PerformanceCounter counter = CounterMap[alias];
            counter.Increment();
        }

        /// <summary>
        /// Increase Performance Counter Value by specified value
        /// </summary>
        /// <param name="alias">Performance Counter Alias</param>
        /// <param name="value">Value</param>
        public void IncreaseCounterBy(string alias, long value)
        {
            PerformanceCounter counter = CounterMap[alias];
            counter.IncrementBy(value);
        }
    }
}